package cn.nawang.ebeim.ui.controller;

import cn.nawang.ebeim.client.dto.ClientDto;
import cn.nawang.ebeim.client.process.Process;
import cn.nawang.ebeim.client.service.ClientService;
import cn.nawang.ebeim.client.version.*;
import cn.nawang.ebeim.persist.domain.DataSource;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

/**
 * Created by GanJc on 2016/2/16.
 */
@RestController
@RequestMapping(value = "/api/version",produces="application/json;charset=UTF-8")
public class VersionController {

    private static final Logger LOG = LoggerFactory.getLogger(VersionController.class);

    @Resource
    private ClientDto dto ;

    @Resource
    private ClientService clientService ;

    @RequestMapping(value = "/data/{dsId}")
    public String data(@PathVariable String dsId){
        System.out.println("@PathVariable String dsId:" + dsId);
        List<Node> nodes = new ArrayList<>();
        VersionTree versionTree = clientService.getVersionTree(dsId,1);
        versionTree.getRoot().setIconSkin("sty01");
        versionTree.getRoot().setOpen(true);
        VersionTreeInfo versionTreeInfo = versionTree.versionTreeInfo();
        List<DirectoryNode> dirNodes = versionTreeInfo.getDirNodes();
        nodes.addAll(dirNodes);
        return JSON.toJSONString(nodes);
    }

    @RequestMapping(value = "/subTree/{dsId}/{version}/{id}")
    public String subTree(@PathVariable String dsId,@PathVariable Integer version,@PathVariable Long id){
        System.out.println("@PathVariable String dsId:" + dsId + "int version:" +version + "long id:" + id);
        clientService.addDownloadProcess(dsId,version,id);
        JSONObject json = new JSONObject();
        json.put("code", "200");
        return json.toString();
    }

    @RequestMapping(value = "/subData/{dsId}/{version}/{id}")
    public String subData(@PathVariable String dsId,@PathVariable Integer version,@PathVariable Long id){
        System.out.println("@PathVariable String dsId:" + dsId + "int version:" +version + "long id:" + id);
        VersionTree versionTree = clientService.getVersionTree(dsId,version);
        List<Node> nodes = new ArrayList<>();
        VersionTreeInfo versionTreeInfo = versionTree.versionTreeInfo();
        List<DirectoryNode> dirNodes = versionTreeInfo.getDirNodes();
        for (DirectoryNode dirNode : dirNodes) {
            if(dirNode.getId() == id){
                Collection<Node> values = dirNode.getChildren().values();
                nodes.addAll(values);
                break;
            }
        }
        return JSON.toJSONString(nodes);
    }


}
